package com.ctgu.controller;


import com.ctgu.common.ResponseResult;
import com.ctgu.model.entity.Admin;
import com.ctgu.model.entity.Company;
import com.ctgu.model.entity.Employee;
import com.ctgu.model.entity.LoginUser;
import com.ctgu.service.IAdminService;
import com.ctgu.service.ICompanyService;
import com.ctgu.service.IEmployeeService;
import com.ctgu.utils.QiFileTools;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.Base64;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {

    @Value("${security.path}")
    private String basePath;

    @Autowired
    private IAdminService adminService;

    @Autowired
    private ICompanyService companyService;

    @Autowired
    private IEmployeeService employeeService;

    /**
     * 文件上传
     * @param file
     * @return
     */

    @RequestMapping(value = "uploadImg", method = RequestMethod.POST)
    public ResponseResult uploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
        LoginUser loginUser=(LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        int id=loginUser.getUser().getId();
        String url= QiFileTools.uploadFile(file,request,id);
        String role_id = loginUser.getUser().getRoleId();
        switch (role_id){
            case "1" :
                Admin byId = adminService.getById(id);
                byId.setImg(url);
                adminService.updateById(byId);
                break;
            case "2":
            case "3":
                Employee byId1 = employeeService.getById(id);
                byId1.setImg(url);
                employeeService.updateById(byId1);
                break;
            case "4":
                Company byId2 = companyService.getById(id);
                byId2.setCompanyImag(url);
                companyService.updateById(byId2);
        }

        return new ResponseResult(200,"修改成功",url);
//        //file是一个零临时变量，需要转纯到别的目录，否则请求结束后删除
//        log.info(file.toString());
//        //原始文件名
//        String originalFileName=file.getOriginalFilename();
//        //获取原始文件后缀
//        String suffix=originalFileName.substring(originalFileName.lastIndexOf("."));
//        //使用UUID重新生成文件名，防止文件被覆盖
//        String fileName= UUID.randomUUID().toString()+suffix;
//        //创建一个目录对象
//        File dir=new File(basePath);
//        if(!dir.exists()){
//            //目录不存在创建一个目录
//            dir.mkdirs();
//        }
//        try {
//            file.transferTo(new File(basePath+fileName));
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

//        String img="data:image/png;base64,"+getImageBase(readFiles(file));
//        LoginUser loginUser=(LoginUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        String roleId=loginUser.getUser().getRoleId();
//        if(roleId.equals("1")){
//            Admin admin=(Admin) loginUser.getUser();
//            admin.setImg(img);
//            adminService.updateById(admin);
//        }
//
//        if(roleId.equals("4")){
//            Company company=(Company) loginUser.getUser();
//            company.setCompanyImag(img);
//            companyService.updateById(company);
//        }
//
//        if(roleId.equals("2")||roleId.equals("3")){
//            Employee employee=(Employee) loginUser.getUser();
//            employee.setImg(img);
//            employeeService.updateById(employee);
//        }
//        return new ResponseResult<>(200,"成功",img);
    }

    public File readFiles(MultipartFile file) {
        int n;
        File newFile = new File(file.getOriginalFilename());
        try (InputStream in = file.getInputStream(); OutputStream os = new FileOutputStream(newFile)) {
            byte[] buffer = new byte[4096];
            while ((n = in.read(buffer, 0, 4096)) != -1) {
                os.write(buffer, 0, n);
            }
            System.out.println("获取文件成功，暂存目录" + newFile.getAbsolutePath());
        } catch (IOException e) {
            System.out.println("获取文件失败");
        }
        return newFile;
    }

    public static String getImageBase(File file) throws Exception {
//        File file = new File(src);
        InputStream in = new FileInputStream(file);
        byte[] data = null;
        try {
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Base64.Encoder encoder = Base64.getEncoder();
        file.delete();
        return encoder.encodeToString(data);
    }
}
